package com.wg.neptune.cluster.strategy;

import com.wg.neptune.cluster.Cluster;
import com.wg.neptune.model.ProviderService;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by mc on 18/6/6.
 */
public class WeightRoundClusterStrategy implements Cluster {

    private  int index = 0;

    private Lock lock = new ReentrantLock();
    /**
     * 加权轮训负载均衡算法
     * 先
     * @param providerServices
     * @return
     */
    public ProviderService select(List<ProviderService> providerServices) {

        ProviderService providerServiceNew = null;
        try {
            lock.lock();
            if(providerServices.size() <= 0){
                return null;
            }
            List<ProviderService> providerServiceList = new ArrayList<ProviderService>();
            for(ProviderService providerService : providerServices){
                for(int i = 0 ; i < providerService.getWeight() ; i++) {
                    providerServiceList.add(providerService.copy());
                }
            }
            if(index >= providerServiceList.size()){
                index = 0;
            }
            providerServiceNew = providerServiceList.get(index);
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
            if(providerServiceNew == null){
                providerServiceNew = providerServices.get(0);
            }
            return providerServiceNew;
    }
}
